package com.jiangruan.javaproject.rpc;

import com.alibaba.fastjson.JSONObject;
import com.jiangruan.javaproject.Constants;
import com.jiangruan.javaproject.bean.GetBestBlockHashentity;
import com.jiangruan.javaproject.request.HttpUtils;
import com.jiangruan.javaproject.service.HotVideoService;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author:huayuzhuo
 * @email:2798866329@qq.com
 * @desc:   该类用于实现通过rpc访问调用bitcoin core的blockhash功能
 * @datatime: 2021/12/18 16:40
 */
public class GetBestBlockHash {

    public static String getBestBlockHash(){

        //准备rpc请求的用户信息及对应的base64格式
        String author = Constants.BITCOIN_RPC_USER + ":" + Constants.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();      //base64编码
        String autthorBase64 = encoder.encodeToString(author.getBytes());

        //请求头的属性设置
        Map<String,String> header = new HashMap<>();
        header.put("Content-Type","application/json");
        header.put("Authorization","Basic "+autthorBase64);

        //准备rpc请求的数据
        Map<String,Object> body = new HashMap<>();  //Object    任意类型
        body.put("id",1001);
        body.put("method",Constants.GETBESTBLOCKHASH);        //"getbestblockhash"
        body.put("params",null);
        body.put("json","2.0");
        byte[] byteBytes = JSONObject.toJSONBytes(body);    //将map集合 body转成数组

        String result = HttpUtils.post(Constants.BITCOIN_RPC_URL,header,byteBytes);

        //反序列化，拿到响应数据中result的值
        GetBestBlockHashentity getBestBlockHashentity = JSONObject.parseObject(result,GetBestBlockHashentity.class);

        return getBestBlockHashentity.result;
    }
}
